use std::env;
use std::ffi::CString;
use std::io;
use std::os::raw::c_char;
use std::thread;
use std::time::Duration;

unsafe extern "C" {
    fn ffmpeg_main(cmdline_str: *const c_char, argc: i32, argv: *const *const c_char) -> i32;
    fn ffmpeg_stop();

}

fn main() {
    println!("Hello, world!");

    //  test_cmd();

    let handle = thread::spawn(|| {
        test_record10();
    });
    println!("==========FFmpeg recording test completed1111.");
    handle.join().unwrap();
    println!("==========FFmpeg recording test completed2222");

    println!("按回车键结束程序...");

    // 方法1：读取整行输入
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("读取输入失败");

    // 方法2：简化版（忽略错误处理）
    // std::io::read_to_string(std::io::stdin()).unwrap();

    println!("程序已结束");
}

fn test_record10() {
    let args = vec![
        "ffmpeg",
        "-loglevel",
        "info",
        "-y",
        "-f",
        "gdigrab",
        "-i",
        "desktop",
        "-r",
        "10",
        "-t",
        "20", // 设置较长时间，等待外部停止
        "-fs",
        "100M",
        "-b:v",
        "1M",
        "test.mp4",
    ];

    let cstrings: Vec<CString> = args.iter().map(|s| CString::new(*s).unwrap()).collect();
    let argv: Vec<*const c_char> = cstrings.iter().map(|cs| cs.as_ptr()).collect();
    let cmdline_str = CString::new(args.join(" ")).unwrap();

    // 启动监视线程，10 秒后发送 'q'
    let monitor = thread::spawn(|| {
        thread::sleep(Duration::from_secs(10));
        println!("🛑 10 seconds elapsed. stop FFmpeg...");
        unsafe {
            ffmpeg_stop();
        }
    });

    // 启动 FFmpeg 主线程（阻塞）
    unsafe {
        ffmpeg_main(cmdline_str.as_ptr(), argv.len() as i32, argv.as_ptr());
    }

    monitor.join().unwrap();
    println!("✅ Recording finished.");
}

fn test_cmd() {
    // 获取命令行参数（包括程序名）
    let args: Vec<String> = env::args().collect();
    //Command line arguments: ["my_ffmpeg_test.exe", "-version"]
    println!("Command line arguments: {:?}", args);

    // 转换成 C 字符串
    let cstrings: Vec<CString> = args
        .iter()
        .map(|s| CString::new(s.as_str()).expect("CString::new failed"))
        .collect();

    // 创建 *const c_char 数组（char**）
    let c_ptrs: Vec<*const c_char> = cstrings.iter().map(|s| s.as_ptr()).collect();

    use std::ptr;

    let cmdline_ptr = ptr::null();
    // 调用 ffmpeg_main
    let ret_code = unsafe { ffmpeg_main(cmdline_ptr, c_ptrs.len() as i32, c_ptrs.as_ptr()) };

    std::process::exit(ret_code);
}
